package com.mayuanfei.springboot10.controller;

import cn.hutool.json.JSONUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redisson测试controller
 *
 * @author 老马
 * @date 2023-06-13 13:19
 */
@RestController
public class RedissonTestController {

    @Resource
    private RedissonClient redissonClient;

    // 通过redisson操作redis
    @GetMapping("/test1")
    public String testRedis1() {
        JsonJacksonCodec jacksonCodec = new JsonJacksonCodec();
        Map<String, Integer> map  = new HashMap<>();
        map.put("laoma", 44);
        map.put("cuidk", 43);
        RMap<Object, Object> lala = this.redissonClient.getMap("lala", jacksonCodec);
        lala.putAll(map);
        RBucket<Object> bucket = this.redissonClient.getBucket("aa:bb:cc", jacksonCodec);
        bucket.set(124);
        return JSONUtil.toJsonStr(lala);
    }

    @GetMapping("/test2")
    public void updateUser(String userId) {
        String lockKey = "user" + userId;
        RLock lock = redissonClient.getLock(lockKey);  //获取锁资源
        try {
            lock.lock(10, TimeUnit.SECONDS);   //加锁,可以指定锁定时间

            //这里写需要处理业务的业务代码
        } finally {
            lock.unlock();   //释放锁
        }
    }




}